package com.edu.dgut.security.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.edu.dgut.dao.administratorsRepository;
import com.edu.dgut.entity.administratorsEntity;
import com.edu.dgut.security.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class SecurityController {

	@Autowired
	private UserService userService;

	@Autowired
	private administratorsRepository administrators;

	@RequestMapping("/")
	public String index() {
		return "/index";
	}

	@RequestMapping("/toLogin")
	public String toLogin() {
		return "login";
	}

	@RequestMapping("/login")
	public String login() {
		//这里什么都不做，由Spring Security负责登录验证
		return "login";
	}

	@RequestMapping("/loginSuccess")
	public String loginSuccess(Model model) {
		return userService.loginSuccess(model);
	}

	@RequestMapping("/main")
	public String main(Model model) {
		return userService.main(model);
	}

	@RequestMapping("/logout")
	public String logout(HttpServletRequest request, HttpServletResponse response) {
		return userService.logout(request, response);
	}

	@RequestMapping("/deniedAccess")
	public String deniedAccess(Model model) {
		return userService.deniedAccess(model);
	}

	//获取当前登录用户信息
	@RequestMapping("/getinfo")
	@ResponseBody
	public Object getinfo() {
		UserDetails userDetails = (UserDetails)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		String name = userDetails.getUsername();
		administratorsEntity administrator = administrators.findByName(name);
		return administrator;
	}
}
